<?php

    class Transaction {

        private $TransactionId;
        private $Customer;
        private $Items; //(<productid> => (Amount => <amount>, Price => <price>))
        private $DateTime;

        public function __construct($id, $customer, $items, $datetime) {
            $this->TransactionId = $id;
            $this->Customer = $customer;
            $this->Items = $items;
            $this->DateTime = $datetime;
        }

        public function __get($key) {
            if(property_exists($this, $key)) {
                return $this->{$key};
            }
            else {
                return NULL;
            }
        }

        public function TotalPrice() {
            $total = 0;
            foreach ($Items as $key => $value)
            $total += $value;
            return $total;
        }

        public function __set($key, $value) {
            throw new Exception('Class is immutable.');
        }

        public static function InsertTransaction($transaction) {
            Connection::Connect();
            if($try = Transaction::ReadTransaction($transaction->TransactionId) != NULL)
                return $try->TransactionId;

            $sql = mysql_query(
                    "
                    INSERT INTO 
                    Transaction (
                        CustomerUsername, 
                        DateTime
                    ) 
                    VALUES (
                        '$transaction->Customer->Username', 
                        NOW()
                    )
                "
            );
            
            if($sql == FALSE)
                return NULL;

            $sql = mysql_query(
                "SELECT LAST_INSERT_ID() as 'LAST_INSERT_ID'"
            );
            
            if($sql == NULL)
                return NULL;

            $insertedid = NULL;
            $rows = mysql_num_rows($sql);
            if($rows == 1) {
                while($row = mysql_fetch_assoc($sql))
                {
                    $insertedid = $row['LAST_INSERT_ID'];
                }
            }

            if($insertedid == NULL)
                return NULL;

            $sqlstatement = "";
            foreach ($transaction->Items as $key => $value) {
                $sqlstatement = $sqlstatement . 
                "
                    INSERT INTO 
                    TransactionItems (
                        TransactionId, 
                        ProductId, 
                        Amount, 
                        Price
                    ) 
                    VALUES (
                        '$insertedid', 
                        '$key', 
                        ".$value['Amount'].", 
                        ".$value['Price']."
                    ); 
                ";
            }
            $sql = mysql_query(
                $sqlstatement
            );
            
            if($sql == FALSE)
                return NULL;

            return $insertedid;
        }

        public static function ReadTransaction($transactionid) {
            Connection::Connect();
            $sql = mysql_query(
                "
                    SELECT 
                        * 
                    FROM 
                        Transaction 
                    WHERE 
                        TransactionId = '$transactionid'
                "
            );
            
            if($sql == NULL)
                return NULL;

            $rows = mysql_num_rows($sql);
            if($rows == 1) {
                while($row = mysql_fetch_assoc($sql))
                {
                    $id = $row['TransactionId'];
                    $customerusername = $row['CustomerUsername'];
                    $items = array();
                    $items_sql = mysql_query(
                        "
                            SELECT 
                                * 
                            FROM 
                                TransactionItems 
                            WHERE 
                                TransactionId = '$id'
                        "
                    );
                    
                    if($items_sql == NULL)
                        return NULL;
                    
                    while($item_row = mysql_fetch_assoc($items_sql))
                    {
                        $item_pid = $item_row['ProductId'];
                        $item_amount = $item_row['Amount'];
                        $item_price = $item_row['Price'];
                        $items[$item_pid] = array('Amount' => $item_amount, 'Price' => $item_price);
                    }
                    $datetime = DateTime::createFromFormat("Y-m-d", $row['DateTime']);

                    return new Transaction($id, Customer::ReadCustomer($customerusername), $items, $datetime);
                }
            }
            return NULL;
        }

        public static function SearchTransaction($transaction) {
            Connection::Connect();
            $where = "WHERE ";
            $conds_present = FALSE;
            if($transaction->TransactionId != NULL) {
                if($conds_present)
                    $where = $where . "AND ";
                $conds_present = TRUE;
                $where = $where . "tr.TransactionId = '$transaction->TransactionId' ";
            }
            if($transaction->Customer != NULL) {
                if($conds_present)
                    $where = $where . "AND ";
                $conds_present = TRUE;
                $where = $where . "tr.CustomerUsername = '$transaction->Customer->Username' ";
            }
            if($transaction->Items != NULL) {
                if($conds_present)
                    $where = $where . "AND ";
                $where = $where . "(";
                $item_present = FALSE;
                foreach ($transaction->Items as $key => $value) {
                    if($item_present)
                        $where = $where . "OR ";
                    $item_present = TRUE;
                    $where = $where . "$key = tritem.ProductId AND tritem.TransactionId = tr.TransactionId ";
                }
                $where = $where . ") ";
            }
            if($transaction->DateTime != NULL) {
                if($conds_present)
                    $where = $where . "AND ";
                $conds_present = TRUE;
                $where = $where . "tr.DateTime = '".$transaction->DateTime->format('Y-m-d')."' ";
            }
            if(!$conds_present)
                $where = "";

            $sql = mysql_query(
                "
                    SELECT DISTINCT
                        *
                    FROM 
                        Transaction 
                "
                .
                $where
            );
            
            if($sql == NULL)
                return NULL;

            $items = array();
            while($row = mysql_fetch_assoc($sql))
            {
                $id = $row['TransactionId'];
                $customerusername = $row['CustomerUsername'];
                $items = array();
                $items_sql = mysql_query(
                    "
                        SELECT 
                            * 
                        FROM 
                            TransactionItems 
                        WHERE 
                            TransactionId = '$id'
                    "
                );

                if($items_sql == NULL)
                    return NULL;

                while($item_row = mysql_fetch_assoc($items_sql))
                {
                    $item_pid = $item_row['ProductId'];
                    $item_amount = $item_row['Amount'];
                    $item_price = $item_row['Price'];
                    $items[$item_pid] = array('Amount' => $item_amount, 'Price' => $item_price);
                }
                $datetime = DateTime::createFromFormat("Y-m-d", $row['DateTime']);

                $items[] = new Transaction($id, Customer::ReadCustomer($customerusername), $items, $datetime);
            }
            return items;
        }

    }

?>